﻿#include "TlvCmdWidget.h"
#include "../TlvCmdPanel/TlvCmdPanel.h"
#include "components/Toast/Toast.h"
#include "stores/DataStroes.h"

#include "components/FWidgets/FMessageBox/FMessageBox.h"
#include <QDebug>

TlvCmdWidget::TlvCmdWidget(QWidget *parent)
    : PageWidget(parent)
{
    initByDataStore();
    connect(this, &PageWidget::pageNameChanged, this, [=](int pageID, const QString& newName){
        panelAt(pageID)->setTitle(newName);
    });
}

TlvCmdWidget::~TlvCmdWidget()
{
    
}

TlvCmdPanel* TlvCmdWidget::addPage(const QString &pageName)
{
    TlvCmdPanel* panel = new TlvCmdPanel(this);
    panel->setTitle(pageName);
    PageWidget::addPage(pageName, panel);
    return panel;
}


QList<CmdPageModel> TlvCmdWidget::toCmdsModel()
{
    QList<CmdPageModel> res;
    for (int i = 0; i < pageCount(); i++) {
        res.push_back(panelAt(i)->toCmdPageModel());
    }
    DataStroes::instance()->tlvPrj()->model().data().cmds = res;  // 保存到stores
    return res;
}

void TlvCmdWidget::initByDataStore()
{
    auto& model = DataStroes::instance()->tlvPrj()->model();
    QString prjPath = DataStroes::instance()->tlvPrj()->latestProject();
    if (model.isValid()) {  // 数据可用，渲染所有表格
        TlvPrjModel& data = model.data();
        for (CmdPageModel& page : data.cmds) {
            TlvCmdPanel* panel = addPage(page.name);
            IICTableWidget* iicTable = panel->iicTable();
            TlvTableWidget* tlvTable = panel->tlvTable();
            for (IICCmdModel& iic : page.iic) {
                iicTable->addIICCmd(iic.title, iic.value.addr, iic.value.hexstring, iic.value.readlen, iic.wait);
            }
            for (TlvCmdModel& tlv : page.tlv) {
                tlvTable->addTlvCmd(tlv.title, tlv.value.tag, tlv.value.hexstring, tlv.wait);
            }
        }
        if (data.cmds.length() > 0) setPage(0);
    } else {  // 数据不可用，添加20行空白表格
        TlvCmdPanel* panel = addPage("Page 1");
        IICTableWidget* iicTable = panel->iicTable();
        TlvTableWidget* tlvTable = panel->tlvTable();
        for (int i = 0; i < 20; i++) {
            iicTable->addNewLine();
            tlvTable->addNewLine();
        }
        setPage(0);
    }
}

TlvCmdPanel *TlvCmdWidget::panelAt(int pageID)
{
    return qobject_cast<TlvCmdPanel*>(PageWidget::panelAt(pageID));
}

void TlvCmdWidget::onAddClicked()
{
    TlvCmdPanel* panel = addPage(tr("New Cmd"));
    IICTableWidget* iicTable = panel->iicTable();
    TlvTableWidget* tlvTable = panel->tlvTable();
    for (int i = 0; i < 20; i++) {
        iicTable->addNewLine();
        tlvTable->addNewLine();
    }
}
